package com.zhongshengnetwork.rightbe.commentstore.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.commentstore.model.CommentStoreClassifyModel;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.model.BookmarkModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.huantansheng.easyphotos.constant.Code.REQUEST_PERMISSION;

public class CommentStoreClassifyActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener {

    private static final int CLASSIFY_PUBLISH = 1001;
    private static final int CLASSIFY_INFO = 1002;
    private String dataContent = "";
    private TopBarView topbar;
    private int pageindex = 0;
    private static final int Records = 20;
    private boolean isGetting = false;
    private boolean isHasMore = false;
    private List<CommentStoreClassifyModel> list;
    private ListView listview;
    private MyAdapter adapter;
    //加载动画
    private AVLoadingIndicatorView avi;
    private RefreshLayout mRefreshLayout;

    private EditText search_edit;
    private Button search_button;
    private ImageView no_data_img;
    private Button publish_button;
    private CommentStoreClassifyModel classifyModel = null;

    private boolean isSelect = false;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CLASSIFY_PUBLISH && resultCode == RESULT_OK){
            mRefreshLayout.autoRefresh();
        }else if (requestCode == CLASSIFY_INFO && resultCode == RESULT_OK){
            mRefreshLayout.autoRefresh();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment_store_classify);
        isSelect = getIntent().getBooleanExtra("isSelect",false);
        avi = (AVLoadingIndicatorView)findViewById(R.id.avi);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        topbar.getTitleView().setClickable(true);
        topbar.getTitleView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hintKeyBoard();
                if (list != null && list.size() > 0){
                    //listview.smoothScrollToPosition(0);
                    listview.setSelection(0);
                }
            }
        });
        topbar.getRightView().setImageResource(R.drawable.whiteadd);
        topbar.getRightView().setClickable(true);
        topbar.getRightView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
//                        && ContextCompat.checkSelfPermission(CommentStoreClassifyActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//                    ActivityCompat.requestPermissions(CommentStoreClassifyActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                            REQUEST_PERMISSION);
//                    ToastUtil.show(CommentStoreClassifyActivity.this,"亲，请开启应用对SD卡的读写权限");
//                    return;
//                }
                Intent intent = new Intent(CommentStoreClassifyActivity.this, NewCommentStoreClassifyActivity.class);
                startActivityForResult(intent, CLASSIFY_PUBLISH);
            }
        });

        pageindex = 0;
        if (list == null){
            list = new ArrayList<CommentStoreClassifyModel>();
        }
        listview=(ListView) findViewById(R.id.classify_listview);
        adapter=new MyAdapter();
        listview.setAdapter(adapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                hintKeyBoard();
                if (list != null && list.size() > 0){
                    if (i >= list.size()){
                        i-=1;
                    }
                    CommentStoreClassifyModel model = list.get(i);
                    if (isSelect == true){
                        Intent intent = new Intent();
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("model", model);//序列化
                        bundle.putBoolean("share",true);
                        intent.putExtras(bundle);//发送数据
                        setResult(RESULT_OK, intent);
                        finish();
                    }else {
                        Intent intent = new Intent(CommentStoreClassifyActivity.this, CommentStoreActivity.class);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("model", model);//序列化
                        bundle.putBoolean("share",true);
                        intent.putExtras(bundle);//发送数据
                        startActivity(intent);
                    }

                }
            }
        });

        listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                hintKeyBoard();
                if (list != null && list.size() > 0){
                    if (i >= list.size()){
                        i -= 1;
                    }
                    classifyModel = list.get(i);
                    final List<String> menu = new ArrayList<>();
                    menu.add("编辑");
                    menu.add("删除");
                    ActionSheetDialog actionSheetDialog = new ActionSheetDialog(CommentStoreClassifyActivity.this)
                            .builder()
                            .setTitle("请选择")
                            .setCancelable(false)
                            .setCanceledOnTouchOutside(true);
                    for (String s : menu){
                        actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if (which > 0){
                                    which -= 1;
                                    String title = menu.get(which);
                                    if (title.equals("编辑")){
                                        if (classifyModel != null){
//                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
//                                                    && ContextCompat.checkSelfPermission(CommentStoreClassifyActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//                                                ActivityCompat.requestPermissions(CommentStoreClassifyActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                                                        REQUEST_PERMISSION);
//                                                ToastUtil.show(CommentStoreClassifyActivity.this,"亲，请开启应用对SD卡的读写权限");
//                                                return;
//                                            }
                                            Intent intent = new Intent(CommentStoreClassifyActivity.this, NewCommentStoreClassifyActivity.class);
                                            Bundle bundle=new Bundle();
                                            bundle.putSerializable("model", classifyModel);//序列化
                                            intent.putExtras(bundle);//发送数据
                                            startActivityForResult(intent, CLASSIFY_PUBLISH);
                                        }
                                    }else if (title.equals("删除")){
                                        CustomDialog dialog = null;
                                        final CustomDialog.Builder builder = new CustomDialog.Builder(CommentStoreClassifyActivity.this);
                                        builder.setTitle("温馨提示");
                                        builder.setMessage("是否要删除评论库："+classifyModel.getClassifyName()+"？");
                                        builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                                deleteClassify();
                                            }
                                        });
                                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                            }
                                        });
                                        dialog = builder.create();
                                        dialog.show();
                                    }
                                }
                            }
                        });
                    }
                    actionSheetDialog.show();
                }
                return true;
            }
        });

        no_data_img = (ImageView)findViewById(R.id.no_data_img);
        publish_button = (Button) findViewById(R.id.publish_button);
        publish_button.setBackgroundResource(AppThemeUtils.getInstance().getButtonBg());
        publish_button.setClickable(true);
        publish_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
//                        && ContextCompat.checkSelfPermission(CommentStoreClassifyActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//                    ActivityCompat.requestPermissions(CommentStoreClassifyActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                            REQUEST_PERMISSION);
//                    ToastUtil.show(CommentStoreClassifyActivity.this,"亲，请开启应用对SD卡的读写权限");
//                    return;
//                }
                Intent intent = new Intent(CommentStoreClassifyActivity.this, NewCommentStoreClassifyActivity.class);
                startActivityForResult(intent, CLASSIFY_PUBLISH);
            }
        });
        mRefreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        //设置 Header 为 贝塞尔雷达 样式
        mRefreshLayout.setRefreshHeader(new BezierRadarHeader(CommentStoreClassifyActivity.this).setEnableHorizontalDrag(true));//BezierRadarHeader
        //设置 Footer 为 球脉冲 样式
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(CommentStoreClassifyActivity.this).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
        mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
        mRefreshLayout.setEnableRefresh(true);//启用刷新
        mRefreshLayout.setEnableLoadMore(true);//启用加载
        //刷新
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //refreshlayout.finishRefresh();
                pageindex = 0;
                getData();
            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //refreshLayout.finishLoadMore();
                getData();
            }
        });

        search_edit = (EditText) findViewById(R.id.search_edit);
        search_button = (Button) findViewById(R.id.search_button);
        search_button.setTextColor(Color.WHITE);
        search_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickSearch(v);
            }
        });

        RelativeLayout classify_layout = (RelativeLayout) findViewById(R.id.classify_layout);
        classify_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
        listview.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        listview.setDivider(new ColorDrawable(AppThemeUtils.getInstance().getBackgroundColor()));
        listview.setDividerHeight(ScreenUtils.dip2px(CommentStoreClassifyActivity.this, 1));

        search_edit.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        search_edit.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        RelativeLayout search_top = (RelativeLayout) findViewById(R.id.search_top);
        search_top.setBackgroundColor(AppThemeUtils.getInstance().getSearchBgColor());
        RelativeLayout search_shape_layout = (RelativeLayout) findViewById(R.id.search_shape_layout);
        search_shape_layout.setBackgroundResource(AppThemeUtils.getInstance().getSearchBackground());

        mRefreshLayout.autoRefresh();
    }


    //删除收藏夹
    private void deleteClassify(){
        if (classifyModel != null){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final HashMap<String, String> map = new HashMap<String, String>();
                    String url = "comment/store/delete.do";
                    map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                    map.put("classifyId", "" + classifyModel.getClassifyId());
                    HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            CommonModel commonModel = GsonTools.getCommonModel(data);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (commonModel.getFlag().equals("1")){
                                        ToastUtil.show(CommentStoreClassifyActivity.this, "删除成功");
                                        mRefreshLayout.autoRefresh();
                                    }else {
                                        CustomApplication.showTip(commonModel, CommentStoreClassifyActivity.this);
                                    }
                                }
                            });
                        }

                        @Override
                        public void onError(String msg) {

                        }
                    });
                }
            }){

            }.start();
        }
    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    private void onClickSearch(View view){
        hintKeyBoard();
        String text = search_edit.getText().toString();
        dataContent = text;
        if (mRefreshLayout != null){
            Log.e("TAG","进来获取数据了刷新界面");
                /*
                @param delayed 开始延时
                @param duration 拖拽动画持续时间
                @param dragRate 拉拽的高度比率（要求 ≥ 1 ）
                */
            mRefreshLayout.autoRefresh(100,300,1f,false);
        }
    }

    private void getData() {
        if (listview == null) {
            return;
        }
        if (isGetting == true) {
            return;
        }
        isGetting = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                final HashMap<String, String> map = new HashMap<String, String>();
                String url = "comment/store/list.do";
                map.put("dataContent", CommonUtils.formatString(dataContent));
                if (CommonUtils.isLogin() == true){
                    map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                }
                map.put("pageIndex",pageindex+"");
                map.put("pageRecord",Records+"");
                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        isGetting = false;
                        CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            final List<CommentStoreClassifyModel> l = GsonTools.getCommentStoreClassifyModel(data);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        //listview.stopLoadMore();
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        list.clear();
                                        //listview.stopRefresh(true);
                                        mRefreshLayout.finishRefresh();
                                    }
                                    if (l != null && l.size() > 0){
                                        no_data_img.setVisibility(View.INVISIBLE);
                                        publish_button.setVisibility(View.INVISIBLE);
                                        if (l.size() >= Records){
                                            //listview.setPullLoadEnable(true);
                                            mRefreshLayout.setEnableLoadMore(true);
                                        }else {
                                            //listview.setPullLoadEnable(false);
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        list.addAll(l);
                                    }else {
                                        isHasMore = false;
                                        //listview.setPullLoadEnable(false);
                                        mRefreshLayout.setEnableLoadMore(false);
                                    }
                                    adapter.notifyDataSetChanged();
                                    if (pageindex == 0){
                                        //listview.smoothScrollToPosition(0);
                                        listview.setSelection(0);
                                        if (list.size() == 0){
                                            no_data_img.setVisibility(View.INVISIBLE);
                                            publish_button.setVisibility(View.VISIBLE);
                                        }
                                    }
                                    if (l != null && l.size() > 0){
                                        pageindex += 1;
                                    }
                                }
                            });
                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        //listview.stopLoadMore();
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        list.clear();
                                        //listview.stopRefresh(true);
                                        mRefreshLayout.finishRefresh();
                                    }
                                    //CustomApplication.showTip(commonModel, CommentStoreClassifyActivity.this);
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        isGetting = false;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (mRefreshLayout.getState() == RefreshState.Loading){
                                    //listview.stopLoadMore();
                                    mRefreshLayout.finishLoadMore();
                                }else {
                                    mRefreshLayout.finishRefresh();
                                }
                            }
                        });
                    }
                });
            }
        }){

        }.start();
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LangDetailActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }


        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            //convertView的复用
            if (convertView == null) {
                convertView = View.inflate(CommentStoreClassifyActivity.this, R.layout.classify_item_layout,null);
            }
            View view=convertView;

            CommentStoreClassifyModel model = list.get(position);
            ImageView classify_icon = (ImageView) view.findViewById(R.id.classify_icon);
            TextView classify_name = (TextView) view.findViewById(R.id.classify_name);
            TextView wzt_count = (TextView) view.findViewById(R.id.wzt_count);
            TextView wzt_title_text = (TextView) view.findViewById(R.id.wzt_title_text);
            wzt_title_text.setText("评论数量");

            View icon_bg = (View) view.findViewById(R.id.icon_bg);
            ImageView private_icon = (ImageView) view.findViewById(R.id.private_icon);
            ImageView author_icon = (ImageView) view.findViewById(R.id.author_icon);
            icon_bg.setVisibility(View.INVISIBLE);
            private_icon.setVisibility(View.INVISIBLE);
            author_icon.setVisibility(View.INVISIBLE);

            RequestOptions options = new RequestOptions().error(AppThemeUtils.getInstance().getDefaultImageBg()).bitmapTransform(new RoundedCorners(5));//图片圆角
            Glide.with(CommentStoreClassifyActivity.this).load(model.getIcon()).apply(options).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(classify_icon);
            classify_name.setText(model.getClassifyName());

            classify_name.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            RelativeLayout classify_item = (RelativeLayout) view.findViewById(R.id.classify_item);
            classify_item.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            LinearLayout classify_item_line = (LinearLayout) view.findViewById(R.id.classify_item_line);
            classify_item_line.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

            wzt_count.setText(""+model.getContentCount());

            return view;
        }
    }
}
